package com.ukao.pad.ui.leaveFactory;


import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.gprinterio.GpDevice;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.pad.R;
import com.ukao.pad.adapter.FactoryListAdapter;
import com.ukao.pad.base.IAdapter;
import com.ukao.pad.base.IPage;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.base.PageWrapper;
import com.ukao.pad.bean.BatchlTabBean;
import com.ukao.pad.bean.PrintAloneBean;
import com.ukao.pad.consts.Constant;
import com.ukao.pad.dialog.DownloadDialogFragment;
import com.ukao.pad.listener.MyOnItemClickListener;
import com.ukao.pad.listener.OnConfirmClickListener;
import com.ukao.pad.listener.OnItemChildClickListener;
import com.ukao.pad.presenter.FactoryTabPesenter;
import com.ukao.pad.printer.CheckPrinterHelper;
import com.ukao.pad.printer.PrinterReceipt;
import com.ukao.pad.ui.setting.SettingFragment;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.FactoryTabView;
import com.ukao.pad.widget.MultipleStatusView;
import com.ukao.pad.widget.MyLRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


public class FactoryListFragment extends MvpFragment<FactoryTabPesenter> implements FactoryTabView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    Unbinder unbinder;
    @BindView(R.id.status_view)
    MultipleStatusView statusView;
    private MyLRecyclerView recyclerView;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ArrayList<BatchlTabBean.ListBean> mData;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private boolean isloadFinish;
    private PageWrapper mPageWrapper;
    private FactoryListAdapter mFactoryListAdapter;
    private int selectPos;
    public BatchlTabBean.ListBean mItem;
    private String searchMsg = "";
    public static final int DETAILAS_RESULT_CODE = 0X10;
    private WebView webView;
    private WebSettings settings;


    public static FactoryListFragment newInstance(String param1, String param2) {
        FactoryListFragment fragment = new FactoryListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected FactoryTabPesenter createPresenter() {
        return new FactoryTabPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_factory_table, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initAdapter();
        initListener();
        return view;
    }
    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        statusView.showContent();
        recyclerView.forceToRefresh();   //用户可见的时候强制刷新
    }

    public void setSearchValue(String searchMsg) {
        this.searchMsg = searchMsg;
        showloadlayout();
    }

    private void showloadlayout() {
        statusView.showContent();
        showProgressDialog();
        startRefresh();

    }

    @Override
    protected void initView() {
        mData = new ArrayList<>();
        IPage page = new IPage() {

            @Override
            public void load(int geIndex, int pageSize) {
                mvpPresenter.BatchOutlist(mParam1, searchMsg, geIndex, pageSize);

            }
        };
        //分页包装器
        mPageWrapper = new PageWrapper<>(mIAdapter, page);

    }



    IAdapter mIAdapter = new IAdapter() {


        @Override
        public void setDataSource(List data, boolean isNextLoad) {
            mFactoryListAdapter.setDatas(data);
            mLRecyclerViewAdapter.notifyDataSetChanged();
            if (!isNextLoad) recyclerView.setNoMore(!isNextLoad);
        }

        @Override
        public void loadMoreFinish(List data, boolean isNextLoad) {

            mFactoryListAdapter.addDatas(data);
            mLRecyclerViewAdapter.notifyDataSetChanged();
            if (!isNextLoad) recyclerView.setNoMore(!isNextLoad);
        }
    };

    @Override
    protected void initAdapter() {
        super.initAdapter();
        recyclerView = (MyLRecyclerView) statusView.findViewById(R.id.lurecycler_view);
        webView = (WebView) statusView.findViewById(R.id.webView);
        initGridRecyclerView(recyclerView, 2);
        mFactoryListAdapter = new FactoryListAdapter(_mActivity, mData);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mFactoryListAdapter);
        recyclerView.setAdapter(mLRecyclerViewAdapter);

    }

    @Override
    protected void initListener() {
        super.initListener();
        recyclerView.setOnRefreshListener(mOnRefreshListener);
        recyclerView.setOnLoadMoreListener(mOnLoadMoreListener);
        mFactoryListAdapter.setOnItemChildClickListener(mOnItemChildListener);
        mFactoryListAdapter.setOnItemClickListener(mOnItemClick);
        statusView.setOnRetryClickListener(onRetryClick);
    }

    private OnItemClickListener mOnItemClick = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            if ( mFactoryListAdapter.getItem(i)==null)return;
            BatchlTabBean.ListBean mitem = mFactoryListAdapter.getItem(i);
            if (getParentFragment() instanceof FactoryTabFragment) {
                ((FactoryTabFragment) getParentFragment()).
                        startForResult(LeaveFactoryFragment.newInstance(mitem, ""), DETAILAS_RESULT_CODE);
            }


        }
    };

    private OnItemChildClickListener mOnItemChildListener = new OnItemChildClickListener() {


        @Override
        public void onChildItemClick(int id, int pos) {
            List<BatchlTabBean.ListBean> mFactoryData = mFactoryListAdapter.getDatas();
            if (mFactoryData.size() >= pos) {
                FactoryListFragment.this.selectPos = pos - 1;
                if (CheckUtils.isNull( mFactoryData.get(selectPos))){
                    return;
                }
                mItem =mFactoryData.get(selectPos);
                switch (id) {
                    case R.id.isFinish:/*完成*/

                        mvpPresenter.finishFactory(mItem.getId() + "");
                        break;

                    case R.id.delete_btn:/*删除*/
                        mvpPresenter.batchIndelete(_mActivity, mItem.getId() + "");
                        break;

                    case R.id.print_receipt_btn:/*打印衣物清单*/
                        if (CheckUtils.isAppInstalled()) {
                            printService(Constant.printUrl(mItem.getId()+""));

                        } else {
                            DownloadDialogFragment mDownloadDialog = DownloadDialogFragment.newInstance("", "");
                            mDownloadDialog.setOnConfirmClickListener(mOnConfirmClickListener);
                            mDownloadDialog.show(getChildFragmentManager(),mDownloadDialog.getClass().getName());
                        }
                        break;
                    case  R.id.easy_print_btn:  /*简易打印*/
                    if (CheckPrinterHelper.isReceipt()){
                        mvpPresenter.printbatchOut(mItem.getId() + "");

                    }
                        break;

                }
            }
        }
    };


    private OnConfirmClickListener   mOnConfirmClickListener=new OnConfirmClickListener() {
        @Override
        public void onChildItemClick(int id, Object msg) {
            if (getParentFragment() instanceof FactoryTabFragment) {
                FactoryTabFragment   mLeaveFactoryFragment=(FactoryTabFragment)getParentFragment();
                mLeaveFactoryFragment.start(SettingFragment.newInstance(2, ""), SINGLETASK);
            }

        }
    };




    /**
     * 重新请求
     */
    View.OnClickListener onRetryClick = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showloadlayout();
        }
    };
    private OnLoadMoreListener mOnLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            mPageWrapper.loadPage(false);
        }
    };
    /**
     * 刷新
     */
    private OnRefreshListener mOnRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {
            startRefresh();
        }


    };


    private void startRefresh() {
        mFactoryListAdapter.getDatas().clear();
        mLRecyclerViewAdapter.notifyDataSetChanged();
        //加载第一页 就为true
        mPageWrapper.loadPage(true);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void loadSuccess(List<BatchlTabBean.ListBean> mBatchlTabBean, Integer totalPage) {
        isloadFinish = true;
        mPageWrapper.addDataSource(mBatchlTabBean, totalPage);
        if (mFactoryListAdapter.getDatas().size() != 0) return;
        if (CheckUtils.isEmpty(mBatchlTabBean)) {
            statusView.showEmpty();
        } else {
            statusView.showContent();
        }
    }

    @Override
    public void showNoNetwork() {
        if (mFactoryListAdapter.getDatas().size() != 0) return;
        statusView.showNoNetwork();


    }

    @Override
    public void refreshFinish() {
        dismissProgressDialog();
        recyclerView.refreshComplete(IPage.DEFAULT_PAGE_SIZE);
    }

    @Override
    public void loadFail(String error) {
        T.show(error);
    }

    @Override
    public void deleteSuccess(String msg) {
        mFactoryListAdapter.remove(selectPos);
        mFactoryListAdapter.notifyDataSetChanged();
    }

    @Override
    public void loadFinishSuccess() {
        mItem.setIsFinish(1);
        mLRecyclerViewAdapter.notifyDataSetChanged();
    }


    /**
     * 打印衣物清单
     *
     * @param mPrintAloneBean
     */
    @Override
    public void loadPrintbatchOutSuccess(PrintAloneBean mPrintAloneBean) {
        GpDevice mGpDevice = new GpDevice();
        PrinterReceipt.getInstance().printleaveFactory(mPrintAloneBean, mGpDevice);

    }


    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case DETAILAS_RESULT_CODE:
                    T.show("");
                    break;


            }

        }
    }


    private void   printService (String loadurl) {


        settings = webView.getSettings();
        Constant.initWeb(settings,webView);
        webView.requestFocus();
        webView.loadUrl(loadurl);
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                    showProgressDialog();
            }

            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dismissProgressDialog();
                createWebPrintJob(webView);
                webView.setLayerType(View.LAYER_TYPE_NONE, null);
                if (!settings.getLoadsImagesAutomatically()) {
                    settings.setLoadsImagesAutomatically(true);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                T.show("加载失败");
                dismissProgressDialog();
            }
        });


    }



    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void createWebPrintJob(WebView webView) {

        try {
            // Get a PrintManager instance
            PrintManager printManager = (PrintManager)_mActivity.
                    getSystemService(Context.PRINT_SERVICE);

            // Get a print adapter instance
            PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
            // Create a print job with name and adapter instance
            String jobName = getString(R.string.app_name) + " Document";
            PrintJob printJob = printManager.print(jobName, printAdapter,
                    new PrintAttributes.Builder().build());
        }catch (Exception e){
            T.show("预览出错");
        }



    }

}
